//
//  SWPictureView.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/6.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SDWebImage

class SWPictureView: UICollectionView {
    /* UICollectionView的布局 */
    @IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
    /* UICollectionView的高度尺寸 */
    @IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
    /* UICollectionView的宽度尺寸 */
    @IBOutlet weak var pictureCollectionViewWeightCons: NSLayoutConstraint!
    
    // MARK: - Life
    /* 从xib获取 */
    override func awakeFromNib() {
        super.awakeFromNib()
        self.dataSource = self
        self.delegate = self
    }
    /* 模型数据 */
    var viewModel: StatusViewModel? {
        didSet {
            /* 更新配图 */
            reloadData()
            /* 更新配图尺寸 */
            let (itemSize,collectionViewSize) = calculateSize()
            /* 更新cell尺寸 */
            if itemSize != CGSizeZero {
                flowLayout.itemSize = itemSize
            }
            /* 更新UICollectionView的尺寸 */
            pictureCollectionViewHeightCons.constant = collectionViewSize.height
            pictureCollectionViewWeightCons.constant = collectionViewSize.width

        }
    }
    // MARK: - 内部控制方法
    /* 获取cell和collectionView的尺寸 */
    private func calculateSize() -> (CGSize,CGSize) {
        let count = viewModel?.thumbnail_pic?.count ?? 0
        /* 没有配图 */
        if count == 0 {
            return (CGSizeZero,CGSizeZero)
        }
        /* 一张配图 */
        if count == 1 {
            let key = viewModel?.thumbnail_pic?.first!.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size,image.size)
        }
        /* 四张配图 */
        let imageWidth: CGFloat = 90
        let imageHeight: CGFloat = 90
        let imageMargin: CGFloat = 10
        if count == 4 {
            let column = 2
            let row = column
            let width = imageWidth * CGFloat(column) + CGFloat(column - 1) * imageMargin
            let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
            return (CGSize(width: imageWidth, height: imageHeight),CGSize(width: width, height: height))
        }
        /* 其他张配图 */
        let column = 3
        let row = (count - 1) / column + 1
        let width = imageWidth * CGFloat(column) + CGFloat(column - 1) * imageMargin
        let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
        return (CGSize(width: imageWidth, height: imageHeight),CGSize(width: width, height: height))
    }

}
// MARK: - DataSource,Delegate
extension SWPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    /* 数据源方法 */
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnail_pic?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! HomePictureCell
        cell.url = viewModel!.thumbnail_pic![indexPath.item]
        return cell
    }
    /* 代理方法 */
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /* 下载进程提示 */
        let url = viewModel?.bmiddle_pic![indexPath.item]
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! HomePictureCell
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (current, total) in
            cell.customImageView.progress = CGFloat(current) / CGFloat(total)
        }) { (_, error, _, _, _) in
            /* 通知 */
            NSNotificationCenter.defaultCenter().postNotificationName(SWPictureBrowserController, object: self, userInfo: ["bmiddle_pic" : (self.viewModel?.bmiddle_pic)!, "indexPath" : indexPath])
        }
    }
}

extension SWPictureView: PictureBrowserPresentationDelegate {
    func browserPresentationWillShowImageView(browserPresentationController: PictureBrowserPresentationController, indexPath: NSIndexPath) -> UIImageView {
        let newImage = UIImageView()
        newImage.contentMode = UIViewContentMode.ScaleAspectFill
        newImage.clipsToBounds = true
        /* 获取的是配图，浏览效果模糊 */
        // let cell = cellForItemAtIndexPath(indexPath) as! HomePictureCell
        // newImage.image = cell.customImageView.image
        /* 获取的是中图，浏览效果清晰 */
        let key = viewModel?.bmiddle_pic![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        newImage.image = image
        newImage.sizeToFit()
        return newImage
    }
    func browserPresentationWillFromFrame(browserPresentationController: PictureBrowserPresentationController, indexPath: NSIndexPath) -> CGRect {
        let cell = cellForItemAtIndexPath(indexPath) as! HomePictureCell
        let frame = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return frame
    }
    func browserPresentationWillToFrame(browserPresentationController: PictureBrowserPresentationController, indexPath: NSIndexPath) -> CGRect {
        let width = UIScreen.mainScreen().bounds.width
        let height = UIScreen.mainScreen().bounds.height
        let cell = cellForItemAtIndexPath(indexPath) as! HomePictureCell
        let image = cell.customImageView.image!
        let scale = image.size.height / image.size.width
        let imageHeight = scale * width
        var offsetY: CGFloat = 0
        if imageHeight < height {
            offsetY = (height - imageHeight) * 0.5
        }
        return CGRect(x: 0, y: offsetY, width: width, height: imageHeight)
    }
}
/* 下载配图 */
class HomePictureCell: UICollectionViewCell {
    var url: NSURL? {
        didSet {
            /* 下载配图 */
            customImageView.sd_setImageWithURL(url)
            /* 判断gif */
            if let flag = url?.absoluteString.lowercaseString.hasSuffix("gif") { 
                gifIconImageView.hidden = !flag
            }
        }
    }
    @IBOutlet weak var customImageView: ZQProgressImageView!
    
    @IBOutlet weak var gifIconImageView: UIImageView!
}

